let websocketUrl = 'ws://162.14.82.204:8080/wuziqiroom';
let websocket = new WebSocket(websocketUrl);

var state = 0 ;
var roomid= "";

websocket.onopen = function(event) {
    console.log("Connected to WebSocket server.");
    let userid = $("#userid").val(); // 假设这是你的userid
    let message = {
        userid: userid,
        state: '0',
        type: '1'
    };
    websocket.send(JSON.stringify(message)); // 将userid转换为JSON字符串并发送
};

websocket.onerror = function(event) {
    console.error("WebSocket error:", event);
    if (event.target.readyState === WebSocket.CLOSED) {
        console.error("Connection closed with error:", event.reason);
    }
};

websocket.onclose = function(event) {
    console.log("WebSocket connection closed:", event);
    let userid = $("#userid").val(); // 假设这是你的userid
    let message = {
        userid: userid,
        state: '-2',
        type: '1'
    };
    websocket.send(JSON.stringify(message)); // 将userid转换为JSON字符串并发送
};

websocket.onmessage = function(event) {
    var data = JSON.parse(event.data);
    if(data.retCode == '0000'){
        alert(data.retDesc);
        if(data.retDesc == '对手已下'){
            if(type == 0){
                type = -1 ;
                hs = true;
            }
            Ds(data.x,data.y);
        }else if(data.retDesc == '对局开始'){
            me = true;
        }else if(data.retDesc == '进入房间'){
            roomid = data.retDesc1;
        }else if(data.retDesc == '对手已离开'){
            if(!over){
                score = "1"
                uploadscore("1");
                over = true
            }
        }
    }
};

var chess = document.getElementById('chess')
var context = chess.getContext('2d')
var me = false
var chessBoard = []
var over = false
var score = ""

var a = -1;
var b = -1;
var type = 0;

var first = false;
var js = false;
var hs = false;

// function find(){
//     if(!first||!me){
//         getDs();
//     }
// }

// 赢法数组
var wins = []

// 赢法的统计数组
var myWin = []
var computerWin = []

for (var i = 0; i < 15; i++) {
    chessBoard[i] = []
    for (var j = 0; j < 15; j++) {
        chessBoard[i][j] = 0
    }
}

// 三维数组
for (var i = 0; i < 15; i++) {
    wins[i] = []
    for (var j = 0; j < 15; j++) {
        wins[i][j] = []
    }
}

// 横线赢法
var count = 0
for (var i = 0; i < 15; i++) {
    for (var j = 0; j < 11; j++) {
        for (var k = 0; k < 5; k++) {
            wins[i][j + k][count] = true
        }
        count++
    }
}

// 竖线赢法
for (var i = 0; i < 15; i++) {
    for (var j = 0; j < 11; j++) {
        for (var k = 0; k < 5; k++) {
            wins[j + k][i][count] = true
        }
        count++
    }
}

// 斜线赢法
for (var i = 0; i < 11; i++) {
    for (var j = 0; j < 11; j++) {
        for (var k = 0; k < 5; k++) {
            wins[i + k][j + k][count] = true
        }
        count++
    }
}

// 散斜线赢法
for (var i = 0; i < 11; i++) {
    for (var j = 14; j > 3; j--) {
        for (var k = 0; k < 5; k++) {
            wins[i + k][j - k][count] = true
        }
        count++
    }
}

console.log(count)

for (var i = 0; i < count; i++) {
    myWin[i] = 0
    computerWin[i] = 0
}

context.strokeStyle = '#000'

var logo = new Image()
logo.src = 'https://s1.ax1x.com/2020/10/25/BeoauD.jpg'
logo.onload = function() {
    context.drawImage(logo, 0, 0, 450, 450)
    drawChessBoard()
}

var drawChessBoard = function() {
    for (var i = 0; i < 15; i++) {
        context.moveTo(15 + i * 30, 15)
        context.lineTo(15 + i * 30, 435)
        context.stroke()

        context.moveTo(15, 15 + i * 30)
        context.lineTo(435, 15 + i * 30)
        context.stroke()
    }
}

var oneStep = function(i, j, me) {
    context.beginPath()
    context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI)
    context.closePath()
    var gradient = context.createRadialGradient(
        15 + i * 30 + 2, 15 + j * 30 - 2, 13,
        15 + i * 30 + 2, 15 + j * 30 - 2, 0,
    )
    if (me) {
        if(!hs){
            gradient.addColorStop(0, '#D1D1D1')
            gradient.addColorStop(1, '#F9F9F9')
        }else{
            gradient.addColorStop(0, '#0A0A0A')
            gradient.addColorStop(1, '#636766')
        }
    } else {
        if(!hs){
            gradient.addColorStop(0, '#0A0A0A')
            gradient.addColorStop(1, '#636766')
        }else{
            gradient.addColorStop(0, '#D1D1D1')
            gradient.addColorStop(1, '#F9F9F9')
        }
    }
    context.fillStyle = gradient
    context.fill()
}

chess.onclick = function(e) {
    if (over) {
        return
    }
    if (!me) {
        alert("等待对手");
        return
    }
    if(type == 0){
        type = 1 ;
        hs = false;
    }

    var x = e.offsetX
    var y = e.offsetY
    var i = Math.floor(x / 30)
    var j = Math.floor(y / 30)
    if (chessBoard[i][j] === 0) {
        if(!first){
            first=!first;
        }

        js = !js;
        a=i;b=j;
        oneStep(i, j, me)
        setQz(i,j);
        chessBoard[i][j] = 1

        for (var k = 0; k < count; k++) {
            if (wins[i][j][k]) {
                myWin[k]++
                computerWin[k] = 6
                if (myWin[k] === 5) {
                    score = "1"
                    uploadscore("1");
                    over = true
                }
            }
        }
        if (!over) {
            me = false
        }
        js = !js;
    }
}

function setQz(u,v){
    var seed = $("#seed").val();
    var userid = $("#userid").val();
    $.ajax({
        type:"post",//请求类型
        url:"/module/wuziqi/setQz",//请求地址
        dataType:"json",//交互的数据类型
        data:{
            userid:userid,
            x:u,
            y:v
        },
        cache:false,//去除请求的缓存
        success:function(){
            console.log("发送"+u+"-"+v);
        }
    });
}

function Ds(a,b) {
    var u = a, v = b
    oneStep(u, v, false)
    chessBoard[u][v] = 2
    for (var k = 0; k < count; k++) {
        if (wins[u][v][k]) {
            computerWin[k]++
            myWin[k] = 6
            if (computerWin[k] === 5) {
                score = "0"
                uploadscore("2");
                over = true
            }
        }
    }
    if (!over) {
        me = true
    }
};

function uploadscore(type){
    if(type == "1"){
        $.ajax({
            type:"post",//请求类型
            url:"/module/wuziqi/wingame",//请求地址
            dataType:"json",//交互的数据类型
            cache:false
        });
        alert("你赢了");
    }else{
        $.ajax({
            type:"post",//请求类型
            url:"/module/wuziqi/losegame",//请求地址
            dataType:"json",//交互的数据类型
            cache:false
        });
        alert("你输了");
    }
}

function goWuziqiBack(){
    var seed = $("#seed").val();
    var userid = $("#userid").val();
    var type = "0";
    $.ajax({
        type:"post",//请求类型
        url:"/module/wuziqi/backHome",//请求地址
        dataType:"json",//交互的数据类型
        data:{
            userid:userid,
            type:type
        },
        cache:false,//去除请求的缓存
        success:function(){
            location.replace("/jump/goWuZiQi");
        }
    });
}
function Wuziqirestart(){
    if(!over){
        alert("对局尚未结束")
    }else{
        context.clearRect(0, 0, chess.width, chess.height);
        me = true;
        chessBoard = [];
        over = false;
        score = "";

        a = -1;
        b = -1;
        type = 0 ;

        hs = false;
        for (var i = 0; i < 15; i++) {
            chessBoard[i] = []
            for (var j = 0; j < 15; j++) {
                chessBoard[i][j] = 0
            }
        }

        for (var i = 0; i < count; i++) {
            myWin[i] = 0
            computerWin[i] = 0
        }

        context.drawImage(logo, 0, 0, 450, 450)
        drawChessBoard()
    }
}